package com.ok.common.exception

import android.net.ParseException
import com.squareup.moshi.JsonDataException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.NoRouteToHostException


object HandleException {

    private var mExceptionListener: ExceptionListener? = null

    fun setListener(listener: ExceptionListener) = apply {
        this.mExceptionListener = listener
    }

    /**
     * 异常统一处理
     */
    fun handleException(e: Throwable): ResponseException {
        val ex: ResponseException
        when (e) {
            is ResponseException -> {
                ex = e
            }

            is HttpException, is NoRouteToHostException -> {
                ex = ResponseException(ErrorCode.HTTP_ERROR, e)
            }

            is JsonDataException, is JSONException, is ParseException -> {
                ex = ResponseException(ErrorCode.PARSE_ERROR, e)
            }

            is ConnectException -> {
                ex = ResponseException(ErrorCode.NETWORK_ERROR, e)
            }

            is javax.net.ssl.SSLException -> {
                ex = ResponseException(ErrorCode.SSL_ERROR, e)
            }

            is java.net.SocketTimeoutException -> {
                ex = ResponseException(ErrorCode.TIMEOUT_ERROR, e)
            }

            is java.net.UnknownHostException -> {
                ex = ResponseException(ErrorCode.TIMEOUT_ERROR, e)
            }

            else -> {
                ex = if (!e.message.isNullOrEmpty()) {
                    ResponseException(1000, e.message!!, e)
                } else {
                    ResponseException(ErrorCode.UNKNOWN, e)
                }
            }
        }
        mExceptionListener?.invoke(ex)
        return ex
    }
}

typealias ExceptionListener = (e: ResponseException) -> Unit
